package com.hoow.shakoow.shake

import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import kotlin.math.abs

class ShakeDetector : SensorEventListener {

    private val SHAKE_THRESHOLD_GRAVITY = 1.7F // 调整此阈值以适应实际情况
    private val SHAKE_SLOP_TIME_MS = 500
    private val SHAKE_COUNT_RESET_TIME_MS = 3000

    private var onShakeListener: (() -> Unit)? = null
    private var shakeTimestamp: Long = 0
    private var shakeCount = 0

    fun setOnShakeListener(listener: () -> Unit) {
        this.onShakeListener = listener
    }

    override fun onSensorChanged(event: SensorEvent) {
        val type = event.sensor.type
        if (type == Sensor.TYPE_ACCELEROMETER) {
            //获取三个方向值
            val values = event.values
            val x = values[0]
            val y = values[1]
            val z = values[2]

            if ((abs(x) > 17 || abs(y) > 17 || abs(z) > 17)) {
                val now = System.currentTimeMillis()
                if (shakeTimestamp + SHAKE_SLOP_TIME_MS > now) {
                    return
                }

                if (shakeTimestamp + SHAKE_COUNT_RESET_TIME_MS < now) {
                    shakeCount = 0
                }

                shakeTimestamp = now
                shakeCount++

                if (shakeCount >= 1) {
                    shakeCount = 0
                    onShakeListener?.invoke()
                }
            }
        }

//        val gX = event.values[0] / SensorManager.GRAVITY_EARTH
//        val gY = event.values[1] / SensorManager.GRAVITY_EARTH
//        val gZ = event.values[2] / SensorManager.GRAVITY_EARTH
//
//        println("x:$gX  y:$gY  z:$gZ")
//        val gForce = sqrt((gX * gX + gY * gY + gZ * gZ).toDouble()).toFloat()
//
//        if (gForce > SHAKE_THRESHOLD_GRAVITY) {
//            val now = System.currentTimeMillis()
//            if (shakeTimestamp + SHAKE_SLOP_TIME_MS > now) {
//                return
//            }
//
//            if (shakeTimestamp + SHAKE_COUNT_RESET_TIME_MS < now) {
//                shakeCount = 0
//            }
//
//            shakeTimestamp = now
//            shakeCount++
//
//            if (shakeCount >= 1) {
//                shakeCount = 0
//                onShakeListener?.invoke()
//            }
//        }
    }

    override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
        // 不需要处理精度变化
    }
}